//
//  TTUserAccountModel.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/7/25.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit

let archivePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("UserAccount.archive")

class TTUserAccountModel: NSObject,NSCoding {
    
//    override init() {
//        super.init()
//        
//        
//    }
    
    //令牌
    var access_token: String?
    
    //令牌有效秒数
    var expires_in: Int = 0{
        didSet{
            
        expiresDate = Date().addingTimeInterval(TimeInterval(expires_in))
        }
    }
    
    //转成有效日期时间
    var expiresDate: Date?
    
    //授权用户UID
    var uid: Int64 = 0
    
    //用户名称
    var name: String?
    //用户头像
    var avatar_large: String?
    
    //kvc
    init(dict: [String: Any]) {
        super.init()
        setValuesForKeys(dict)
    }
    
    
    //归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    
    //存储用户信息
    func saveUserAccount() {
        NSKeyedArchiver.archiveRootObject(self, toFile: archivePath)
    }
    
    //加载用户信息, 类方法
    class func loadUserAccount() -> TTUserAccountModel? {
        return NSKeyedUnarchiver.unarchiveObject(withFile: archivePath) as? TTUserAccountModel
    }
    
    

    //防止崩溃
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
}
